<template>
  <div class="rechargePackageConfig h100" v-loading="loading">
    <div class="pageContent">
      <el-form
        :model="ruleForm"
        :inline="true"
        ref="ruleForm"
        label-width="80px"
      >
        <el-row :gutter="11" class="fileSearch">
          <!-- <el-form-item label="手机号:" prop="loginPhone">
            <el-input v-model="ruleForm.loginPhone" clearable></el-input>
          </el-form-item>
          <el-form-item label="姓名:" prop="fullName">
            <el-input v-model="ruleForm.fullName" clearable></el-input>
          </el-form-item> -->
          <el-form-item>
            <!-- <el-button
              icon="el-icon-search"
              type="primary"
              @click="onLoad('search')"
            >
              查询
            </el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery"
              >重置</el-button
            > -->
            <el-button
              icon="el-icon-plus"
              type="success"
              @click="dialogVisible = true"
              >新增</el-button
            >
          </el-form-item>
        </el-row>
        <div class="table_wrapper">
          <el-table
          :data="tableData"
          border
          :header-cell-style="{
            background: 'rgb(246,247,251)',
            color: '#606266'
          }"
          stripe
          class="defaultTableHeight"
        >
          <el-table-column type="index" label="编号" width="50">
          </el-table-column>
          <el-table-column prop="packageName" align="center" label="套餐名称">
          </el-table-column>
          <el-table-column align="center" label="套餐金额">
            <template slot-scope="scope">
              {{ (scope.row.packageAmount / 100).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="sacrificeCoinNum"
            align="center"
            label="祭祀币个数"
          >
          </el-table-column>
          <el-table-column
            prop="commemorativeCoinNum"
            align="center"
            label="纪念币个数"
          >
          </el-table-column>
          <el-table-column align="center" label="注册日期">
            <template slot-scope="scope">
              {{ scope.row.gmtCreate | timestampToTime }}
            </template>
          </el-table-column>

          <!-- <el-table-column prop="asLogin" align="center" label="禁用启用">
            <template slot-scope="scope">
              <el-button
                :type="scope.row.asLogin === 0 ? 'danger' : 'success'"
                size="mini"
                >{{ scope.row.asLogin === 0 ? "禁用" : "启用" }}
              </el-button>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" align="center" width="300px">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="updata(scope.row)"
                >编辑</el-button
              >
              <el-button type="danger" size="mini" @click="del(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <p style="text-align: right;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pager.currentPage"
            :page-size="pager.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            background
            layout="total,sizes,prev, pager, next, jumper"
            :total="pager.total"
          >
          </el-pagination>
        </p>
        </div>
      </el-form>
    </div>
    <el-dialog
      :title="titleName"
      :visible.sync="dialogVisible"
      width="600px"
      v-dialogDrag
      @close="closeDialog"
      @opened="opened"
    >
      <el-form
        ref="goodsForm"
        :model="goodsForm"
        :rules="goodsFormRules"
        label-width="80px"
      >
        <el-form-item label="套餐名称" prop="packageName">
          <el-input ref="input" v-model="goodsForm.packageName"></el-input>
        </el-form-item>
        <el-form-item label="祭祀币">
          <el-input v-model="goodsForm.sacrificeCoinNum"></el-input>
        </el-form-item>
        <el-form-item label="纪念币">
          <el-input v-model="goodsForm.commemorativeCoinNum"></el-input>
        </el-form-item>
        <el-form-item label="套餐金额" prop="packageAmount">
          <el-input
            v-model="goodsForm.packageAmount"
            @blur="moneyType(goodsForm.packageAmount)"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  deal_list,
  deal_operation,
  deal_delete
} from "@/api/adminConfig/rechargePackageConfig";
export default {
  name: "rechargePackageConfig",
  data() {
    const isNumber = (rule, value, callback) => {
      if (!Number.isInteger(+value)) {
        callback(new Error("请输入数字值"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      dialogVisible: false,
      titleName: "添加套餐",
      ruleForm: {
        loginPhone: "",
        fullName: ""
      },
      pager: {
        pageSize: 20,
        total: 1,
        currentPage: 1
      },
      goodsForm: {
        id: "",
        packageName: "", //套餐名称
        packageAmount: "", //套餐金额
        sacrificeCoinNum: 0, // 祭祀币
        commemorativeCoinNum: 0 // 纪念币
      },
      tableData: [],
      goodsFormRules: {
        packageName: [
          { required: true, message: "请输入套餐名称", trigger: "blur" }
        ],
        packageAmount: [
          { required: true, message: "请输入套餐金额", trigger: "blur" }
        ],
        sacrificeCoinNum: [
          { required: true, message: "请输入祭祀币数量", trigger: "blur" },
          { validator: isNumber, trigger: "blur" },
          { validator: isNumber, trigger: "change" }
        ],
        commemorativeCoinNum: [
          { validator: isNumber, trigger: "blur" },
          { validator: isNumber, trigger: "change" }
        ]
      }
    };
  },
  mounted() {
    this.onLoad();
  },
  filters: {
    // timestampToTime(date) {
    //   var nowdate = new Date(date)
    //     .toJSON()
    //     .substr(0, 19)
    //     .replace("T", " ");
    //   return nowdate;
    // }
  },

  //注销window.onresize事件
  destroyed() {},
  methods: {
    async onLoad() {
      this.loading = true;
      let postData = {
        loginPhone: this.ruleForm.loginPhone,
        fullName: this.ruleForm.fullName,
        auditState: this.ruleForm.auditState,
        pageSize: this.pager.pageSize,
        currentPage: this.pager.currentPage
      };
      try {
        const res = await deal_list(postData);
        console.log(res, 200);
        this.loading = false;
        if (res.code !== "2000") {
          this.$message(res.msg ? res.msg : "数据读取失败");
          return;
        }

        this.tableData = res.data;
        this.pager.pageSize = res.pageSize;
        this.pager.total = res.total;
        this.pager.currentPage = res.currentPage;
        //数据读取成功
      } catch (err) {
        console.log(err, 404);
        // this.$message(err);
        this.loading = false;
        this.tableData = [];
      }
    },
    // 修改
    updata(info) {
      this.titleName = "修改套餐信息";
      this.dialogVisible = true;
      let data = JSON.parse(JSON.stringify(info));
      data.packageAmount = this.moneyType(data.packageAmount / 100);
      this.goodsForm = data;
    },
    // 保存
    async onSubmit() {
      this.$refs["goodsForm"].validate(async valid => {
        if (valid) {
          this.loading = true;
          let postData = JSON.parse(JSON.stringify(this.goodsForm));
          postData.packageAmount = +postData.packageAmount * 100;
          console.log(postData, "postData");
          // return;
          try {
            const res = await deal_operation(postData);
            this.loading = false;
            console.log(res, 200);
            if (res.code !== "2000") {
              this.$message.error(res.msg ? res.msg : "保存失败");
              return;
            }
            this.$message.success("保存成功");
            this.closeDialog();
            this.onLoad();
          } catch (err) {
            this.loading = false;
            this.$message.error(err.msg);
            console.log(err, 404);
          }
        }
      });
    },
    // 删除
     del(id) {
       this.$confirm('此操作将永久删除该套餐, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.loading = true;
      let postData = { ids: [id] };
      try {
        const res = await deal_delete(postData);
        console.log(res, 200);
        this.loading = false;
        if (res.code !== "2000") {
          this.$message.error(res.msg ? res.msg : "删除失败");
          return;
        }
        this.$message.success("删除成功");
        this.onLoad();
      } catch (err) {
        console.log(err);
        this.$message(err);
        this.loading = false;
      }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      
    },
    // 打开弹窗时的回调
    opened() {
      this.$refs.input.focus();
    },
    // 关闭弹窗的回调
    closeDialog() {
      this.goodsForm = {
        id: "",
        packageName: "", //套餐名称
        packageAmount: "", //套餐金额
        sacrificeCoinNum: 0, // 祭祀币
        commemorativeCoinNum: 0 // 纪念币
      };
      this.$refs["goodsForm"].resetFields();
      this.dialogVisible = false;
      this.titleName = "添加套餐信息";
    },
    // 金额数据处理
    moneyType(num) {
      let money = Math.round((num == "" ? 0 : num) * 100) / 100;
      money = money.toFixed(2);
      return (this.goodsForm.packageAmount = money);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["ruleForm"].resetFields();
      this.onLoad();
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function(size) {
      this.pager.pageSize = size;
      this.onLoad();
    },
    handleCurrentChange: function(currentPage) {
      this.pager.currentPage = currentPage;
      this.onLoad(); //点击第几页
    }
  }
};
</script>

<style lang="scss" scoped>
.fileSearch {
  .el-button {
    margin-left: 20px;
  }
}
</style>
